﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using FFIV.Lib.IView.Categories;
using FFIV.Lib.Model;

public partial class Views_Categories_Manage : UserControl, IManageCategories
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}

	public CategoryNode Categories
	{
		set
		{
			ManageTV.CategoryTV.Nodes.Clear();
			BuildCategoryTreeView(value.Children, ManageTV.CategoryTV.Nodes);
			ManageTV.CategoryTV.ExpandAll();
		}
	}

	public string ModifiedCategoryName
	{
		get { return tb_ModifiedName.Text; }
	}

	public int ModifiedCategoryId
	{
		get
		{
			if (ManageTV.CategoryTV.CheckedNodes.Count == 1)
			{
				return Convert.ToInt32(ManageTV.CategoryTV.CheckedNodes[0].Value);
			}
			return 0;
		}
	}

	public int ModifiedCategoryParentId
	{
		get
		{
			if (ManageTV.CategoryTV.CheckedNodes.Count == 1 && ManageTV.CategoryTV.CheckedNodes[0].Parent != null)
			{
				return Convert.ToInt32(ManageTV.CategoryTV.CheckedNodes[0].Parent.Value);
			}
			return 0;
		}
	}

	public event EventHandler AddCategory
	{
		add { btn_AddCategory.Click += value; }
		remove { btn_AddCategory.Click -= value; }
	}

	public event EventHandler AddChildCategory
	{
		add { btn_AddChildCategory.Click += value; }
		remove { btn_AddChildCategory.Click -= value; }
	}

	public event EventHandler EditCategory
	{
		add { btn_EditCategory.Click += value; }
		remove { btn_EditCategory.Click -= value; }
	}

	public event EventHandler DeleteCateory
	{
		add { btn_DeleteCategory.Click += value; }
		remove { btn_DeleteCategory.Click -= value; }
	}

	private void BuildCategoryTreeView(IEnumerable<CategoryNode> datas, TreeNodeCollection items)
	{
		foreach (CategoryNode data in datas)
		{
			TreeNode item = new TreeNode();
			item.Text = string.Format("{0} ({1})", data.Name, data.ArticleCount);
			item.Value = data.Id.ToString();

			if (data.Children.Count > 0)
			{
				// 使得有子结点的项目点击展开，叶子结点不能点击
				item.SelectAction = TreeNodeSelectAction.Expand;
			}
			else
			{
				// 使得无子结点的项目不能点击
				item.SelectAction = TreeNodeSelectAction.None;
			}

			items.Add(item);

			BuildCategoryTreeView(data.Children, item.ChildNodes);
		}
	}
}
